import axios from "axios"
import store from "@/store"
import router from "../router";
import { Message } from "element-ui";

const http = axios.create({
    baseURL:process.env.VUE_APP_MOCK==='true'?"":process.env.VUE_APP_BASE_URL, //"http://localhost:9003",
    timeout: 3000, // 请求超时时间
    headers: {
        "Content-Type": "application/json;charset=UTF-8"
    }
});


//请求拦截器
http.interceptors.request.use((config) => {
    const token = store.state.token
    if (token) {
        config.headers.Authorization = token;
    } else {
        router.currentRoute.fullPath !== "/login" && router.replace('/login')
    }
    return config
}, (error) => {
    console.log(error)
    return Promise.reject(error)
})

//响应拦截器
http.interceptors.response.use((response) => {
    console.log(response)
    if (response.data.code === 400) {
        //判断token失效
        store.commit('setToken', '')
        router.replace('/login')
    }
    return response
}, (error) => {
    console.log(error)
    Message.error('请求失败')
    return Promise.reject(error)
})

export default http